<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * SystemSetting模型
 */
class SystemSetting extends Model
{
    // 设置表名
    protected $name = 'system_settings';
    
    // 设置字段信息
    protected $schema = [
        'id'               => 'int',
        'key'              => 'string',
        'value'            => 'string',
        'description'      => 'string',
        'create_time'      => 'datetime',
        'update_time'      => 'datetime',
    ];
    
    // 设置自动时间戳
    protected $autoWriteTimestamp = true;
    
    /**
     * 获取指定键的设置值
     *
     * @param string $key 设置键名
     * @param mixed $default 默认值
     * @return mixed
     */
    public static function getSettingValue(string $key, $default = null)
    {
        $setting = self::where('key', $key)->find();
        return $setting ? $setting->value : $default;
    }
    
    /**
     * 设置指定键的值
     *
     * @param string $key 设置键名
     * @param mixed $value 设置值
     * @param string $description 设置描述
     * @return bool
     */
    public static function setSettingValue(string $key, $value, string $description = null)
    {
        $setting = self::where('key', $key)->find();
        
        if ($setting) {
            $data = ['value' => $value];
            if ($description !== null) {
                $data['description'] = $description;
            }
            return $setting->save($data);
        } else {
            return (bool) self::create([
                'key' => $key,
                'value' => $value,
                'description' => $description ?? $key,
            ]);
        }
    }
    
    /**
     * 获取纸条单价
     *
     * @return float
     */
    public static function getNotePrice() : float
    {
        return (float) self::getSettingValue('note_price', 1);
    }
    
    /**
     * 获取所有系统设置
     *
     * @return array
     */
    public static function getSettings() : array
    {
        $settings = self::select()->toArray();
        $result = [];
        
        foreach ($settings as $setting) {
            $result[$setting['key']] = $setting['value'];
        }
        
        return $result;
    }
} 